<template>
  <div class="box">
    <div class="search-history">历史搜索</div>
    <div v-for="item in dataList" :key="item" @click="handleClick(item)" class="items">
      <span>
        <i class="bi bi-clock-history"></i>
        {{ item }}
      </span>
    </div>
    <div @click="handleClear" class="clear">清除历史记录</div>

  </div>
</template>
<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import useHistoryStore from '@/store/search-historyStore.ts'
// import useHistoryStore from '@/store/historyStore.ts'
import useSearchStore from '@/store/search-searchStore.ts'




const store_history = useHistoryStore()
const store_search = useSearchStore()


// 在给 dataList 赋值前，"先" 将 会话存储 中的数据给 History
store_history.fetch()

// 给 dataList 赋值
const dataList = ref(store_history.addHistory())

// 判断历史记录列表中的搜索历史，让列表中只显示 8 条数据
if (dataList.value.length === 9) dataList.value.pop()

// 在组件销毁时，将 History 的数据存储到 会话存储 中
onUnmounted(() => {
  store_history.storage()
})



// 点击历史记录后，将点击的内容提升值历史记录列表中的第一个
const handleClick = (item: string) => {

  // 搜索框中显示点击的历史记录
  store_search.search = item

  // 为了防止重新刷新页面，将dataList重新赋值为原来的数据，所以删除点击的历史记录
  delete store_history.History[item]

  // 重新添加数据到 History 对象的最后面
  store_history.History[item] = item
}



// 清空搜索历史
const handleClear = () => {

  // 销毁 会话存储 中的数据
  sessionStorage.clear()

  // 将 History 赋空
  store_history.History = {}

  // 对 页面 中的历史记录清空
  dataList.value = store_history.addHistory()
}

</script>

<style scoped lang="scss">
.box {

  background-color: white;
  margin-top: 1.4vh;
  height: calc(100vh - 20vh - 7vh - 1.4vh - 40px);

  .search-history {
    color: rgb(133, 133, 133);
    height: 7vh;
    display: flex;
    align-items: center;
    padding-left: 3.5vw;
  }

  .items {
    height: calc((100vh - 20vh - 7vh - 1.4vh - 40px - 7vh - 6vh)/8);
    display: flex;
    align-items: center;
    font-size: 3.8vw;

    span {
      padding-left: 3vw;

      i {
        margin-right: 1vw;
        color: rgb(178, 174, 174);
      }
    }
  }



  .clear {
    text-align: center;
    color: rgb(133, 133, 133);
    height: 6vh;
    display: flex;
    justify-content: center;
    align-items: center;
  }

}
</style>@/store/search-historyStore@/store/search-searchStore